package com.example.night.service.ApiService;

import com.example.night.data.Order.Order;
import com.example.night.data.Order.OrderPackage;
import com.example.night.data.Order.OrderResponse;
import com.example.night.service.ApiService.Token.TokenService;
import com.example.night.service.ApiService.Token.TokenUpdatedEvent;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.JsonNode;
import com.fasterxml.jackson.databind.ObjectMapper;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.event.EventListener;
import org.springframework.http.*;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.jar.JarException;

@Slf4j
@Service
public class OrderService {

    private static final String API_URL = "https://api.jiutool.com/institutionHomeTwo/order/es_lists";
    private static final Logger logger = LoggerFactory.getLogger(InfluencerSummaryService.class);

    private final RestTemplate restTemplate;
    private final TokenService tokenService;
    private final ObjectMapper objectMapper;
    private final Lock lock = new ReentrantLock();
    private String token;


    public OrderService(RestTemplate restTemplate, TokenService tokenService, ObjectMapper objectMapper) {
        this.restTemplate = restTemplate;
        this.tokenService = tokenService;
        this.objectMapper = objectMapper;
        token = tokenService.getToken();
    }
    public int getFlowpointFlag(String flow_point) {
        int flag = -1;  // 默认值，表示无效的 flow_point
        switch (flow_point) {
            case "PAY_SUCC":
                flag = 0;  // PAY_SUCC
                break;
            case "REFUND":
                flag = 1;  // SETTLE
                break;
            case "SETTLE":
                flag = 2;  // REFUND
                break;
            case "CONFIRM":
                flag = 3;  // CONFIRM
                break;
            default:
                flag = -1;  // 如果没有匹配到，返回 -1
                break;
        }
        return flag;
    }
    public String getFlowpoint(int flag) {
        String flow_point = "";
        switch (flag) {
            case 0:
                flow_point = "PAY_SUCC"; //支付完成
                break;
            case 1:
                flow_point = "REFUND";  //退款
                break;
            case 2:
                flow_point = "SETTLE";  //结算
                break;
            case 3:
                flow_point = "CONFIRM"; //确认收货
                break;
            default:
                flow_point = "";
                break;
        }
        return flow_point;
    }
    @EventListener
    public void handleTokenUpdated(TokenUpdatedEvent event) {
        token = event.getNewToken();
    }

    public OrderPackage packageOrder(Order order) {
        OrderPackage orderPackage = new OrderPackage();

        orderPackage.setRelateOrderNo(order.getOrderId());

        orderPackage.setRelateProductImg(order.getProductImg());
        orderPackage.setRelateProductName(order.getProductName());
        orderPackage.setRelateProductId(order.getProductId());

        orderPackage.setPromoterId(order.getFInstitutionId() != "" ? order.getFInstitutionId() : order.getAuthorShortId());
        orderPackage.setPromoteName(order.getFInstitutionName() != "" ? order.getFInstitutionName() : order.getAuthorAccount());

        orderPackage.setOrderPayTime(order.getPaySuccessTime());
        orderPackage.setOrderConfirmTime(order.getSettleTime());
        orderPackage.setStatus(getFlowpointFlag(order.getFlowPoint()));

        orderPackage.setSysRelateServiceMoneyIn(order.getInEstimatedCommission());
        orderPackage.setSysSettleMoney(order.getTotalPayAmount());

        return orderPackage;
    }

    public Map<String, Object> fetchOrders(String startTime, String endTime, int page, String title, int flow_point, int extend_type, String promoterId, int flag) {
        try {
            token = tokenService.getToken();
            if (token == null || token.isEmpty()) {
                logger.error("获取达人数据失败：Token 为空，请检查登录状态");
                return Map.of(
                        "success", false,
                        "message", "未登录"
                );
            }
            // 构建请求 URL
            String url = UriComponentsBuilder.fromHttpUrl(API_URL)
                    .queryParam("page", page)
                    .queryParam("limit", 10)
                    .queryParam("time_field", "pay_success_time")
                    .queryParam("start_time", startTime)
                    .queryParam("end_time", endTime)
                    .queryParam("title", title)
                    .queryParam("flow_point", flow_point == 4 ? "" : getFlowpoint(flow_point))
                    .queryParam("order_id", "")
                    .queryParam("author_account", promoterId)
                    .queryParam("drsw_account_id", "")
                    .queryParam("zsyy_account_id", "")
                    .queryParam("extend_type", extend_type == 3 ? "" : extend_type)
                    .queryParam("is_drsw", "")
                    .queryParam("is_zsyy", "")
                    .queryParam("f_institution_name", "")
                    .queryParam("except_status", "")
                    .queryParam("type", "in")
                    .toUriString();

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);  // 设置 Authorization 请求头
            headers.set("X-Csrf-Token", token);     // 设置 CSRF Token
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 构造 HTTP 请求
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);

//            log.info("请求第 {} 页订单数据: {}", page, url);
            // 发送 GET 请求
            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
//            log.info("API 返回数据: {}", response.getBody());

            // 解析 JSON 响应
            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                OrderResponse orderResponse = null;
                try {
                    orderResponse = objectMapper.readValue(response.getBody(), OrderResponse.class);
                }catch (JsonProcessingException e) {
                    System.out.println(url);
                    System.out.println(response.getBody());
                }

                if (orderResponse.getData() != null) {
                    List<Order> orders = orderResponse.getData().getData();
                    List<OrderPackage> orderPackages = new ArrayList<>();
                    int lastPage = orderResponse.getData().getLastPage();
                    for (Order order :orders) {
                        OrderPackage orderPackage = packageOrder(order);

                        orderPackages.add(orderPackage);
                    }

                    return Map.of(
                            "success", true,
                            "message", "获取成功",
                            "totalOrders", orderPackages.size(),
                            "orders", orderPackages,
                            "lastpage", lastPage
                    );
                }
            } else {
                log.error("获取订单数据失败，状态码: {}", response.getStatusCode());
            }

        } catch (Exception e) {
            log.error("获取订单数据请求失败", e);
        }
        return Map.of(
                "success", false,
                "message", "获取失败"
        );
    }
    private List<OrderPackage> responseToListOrderPackage(ResponseEntity<String> response) {
        List<OrderPackage> orderPackages = new ArrayList<>();

        if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
            try {
                OrderResponse orderResponse = objectMapper.readValue(response.getBody(), OrderResponse.class);
                if (orderResponse.getData() != null) {
                    List<Order> orders = orderResponse.getData().getData();
                    for (Order order : orders) {
                        OrderPackage orderPackage = packageOrder(order);
                        orderPackages.add(orderPackage);
                    }
                }
            } catch (JsonProcessingException e) {
                logger.error("订单数据解析失败，响应内容: {}", response.getBody(), e);
            }
        } else {
            logger.error("订单请求失败，状态码: {}", response.getStatusCode());
        }

        return orderPackages;
    }
    private String buildOrderUrl(int page, String startTime, String endTime, String promoterId) {
        return UriComponentsBuilder.fromHttpUrl(API_URL)
                .queryParam("page", page)
                .queryParam("limit", 10)
                .queryParam("time_field", "pay_success_time")
                .queryParam("start_time", startTime)
                .queryParam("end_time", endTime)
                .queryParam("title", "")
                .queryParam("flow_point", "")
                .queryParam("order_id", "")
                .queryParam("author_account", promoterId)
                .queryParam("drsw_account_id", "")
                .queryParam("zsyy_account_id", "")
                .queryParam("extend_type", "")
                .queryParam("is_drsw", "")
                .queryParam("is_zsyy", "")
                .queryParam("f_institution_name", "")
                .queryParam("except_status", "")
                .queryParam("type", "in")
                .toUriString();
    }

    public List<OrderPackage> getOrders(String startTime, String endTime, String promoterId) {
        try {
            // 获取 Token
            token = tokenService.getToken();
            if (token == null || token.isEmpty()) {
                logger.error("获取订单数据失败：Token 为空，请检查登录状态");
                return Collections.emptyList();
            }

            int page = 1;
            int lastPage = 1;

            // 构造请求头
            HttpHeaders headers = new HttpHeaders();
            headers.set("Authorization", "Bearer " + token);  // 设置 Authorization 请求头
            headers.set("X-Csrf-Token", token);  // 设置 CSRF Token
            headers.set("Content-Type", "application/x-www-form-urlencoded; charset=UTF-8");

            // 构造 HTTP 请求
            HttpEntity<String> requestEntity = new HttpEntity<>(headers);
            List<OrderPackage> orderPackages = new ArrayList<>();

            // 获取第一页订单数据
            String url = buildOrderUrl(page, startTime, endTime, promoterId);

            ResponseEntity<String> response = restTemplate.exchange(url, HttpMethod.GET, requestEntity, String.class);
            JsonNode jsonResponse = objectMapper.readTree(response.getBody());

            // 获取 "data" 字段并判断是否为空
            JsonNode data = jsonResponse.get("data");
            if (data.isArray() && data.size() == 0) {
                return Collections.emptyList();
            }

            if (response.getStatusCode() == HttpStatus.OK && response.getBody() != null) {
                OrderResponse orderResponse = null;
                try {
                    orderResponse = objectMapper.readValue(response.getBody(), OrderResponse.class);
                } catch (JsonProcessingException e) {
                    logger.error("第一页订单数据解析失败，URL: {}, 响应内容: {}", url, response.getBody(), e);

                    return Collections.emptyList();
                }

                if (orderResponse != null && orderResponse.getData() != null) {
                    List<Order> orders = orderResponse.getData().getData();
                    lastPage = orderResponse.getData().getLastPage();
//                    logger.info("第一页订单数据获取成功，共 {} 条订单，最后页码：{}", orders.size(), lastPage);

                    for (Order order : orders) {
                        OrderPackage orderPackage = packageOrder(order);
                        orderPackages.add(orderPackage);
                    }
                } else {
                    logger.warn("第一页订单数据为空或获取失败");
                }
            } else {
                logger.error("第一页请求失败，状态码: {}", response.getStatusCode());
            }

            // 如果只有一页，直接返回结果
            if (lastPage <= 1) {
                return orderPackages;
            }

            // 创建线程池
            ExecutorService executorService = Executors.newFixedThreadPool(8);  // 可根据需求调整线程数
            List<Future<List<OrderPackage>>> futures = new ArrayList<>();

            // 从第二页开始多线程处理
            for (int currentPage = 2; currentPage <= lastPage; currentPage++) {
                final int pageNum = currentPage;
                futures.add(executorService.submit(() -> {
                    try {
                        String pageUrl = buildOrderUrl(pageNum, startTime, endTime, promoterId);

                        ResponseEntity<String> pageResponse = restTemplate.exchange(pageUrl, HttpMethod.GET, requestEntity, String.class);
//                        logger.info("正在获取第 {} 页订单数据", pageNum);
                        return responseToListOrderPackage(pageResponse);
                    } catch (Exception e) {
                        logger.error("获取第 {} 页订单数据失败", pageNum, e);
                        return Collections.emptyList();
                    }
                }));
            }

            // 等待所有任务完成并收集结果
            for (Future<List<OrderPackage>> future : futures) {
                try {
                    orderPackages.addAll(future.get());
                } catch (InterruptedException e) {
                    logger.error("线程被中断：{}", e.getMessage());
                    Thread.currentThread().interrupt();
                } catch (ExecutionException e) {
                    logger.error("获取分页订单数据失败", e);
                }
            }

            // 优雅关闭线程池
            executorService.shutdown();
            try {
                if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                    executorService.shutdownNow();
                    if (!executorService.awaitTermination(60, TimeUnit.SECONDS)) {
                        logger.error("线程池未能正常关闭");
                    }
                }
            } catch (InterruptedException e) {
                logger.error("线程池关闭中断", e);
                executorService.shutdownNow();
                Thread.currentThread().interrupt();
            }

//            logger.info("订单数据获取完成，共获取到 {} 条订单", orderPackages.size());
            return orderPackages;

        } catch (Exception e) {
            logger.error("获取订单数据请求失败", e);
        }

        return Collections.emptyList();
    }

}
